from django.shortcuts import render, redirect, HttpResponse
from rbac import models
from rbac.service.init_permission import init_permission


def login(request):
    if request.method == 'POST':
        #   获取用户名和密码
        user = request.POST.get('username')
        pwd = request.POST.get('password')
        # 数据库校验用户名和密码是否正确
        user_obj = models.User.objects.filter(username=user, password=pwd).first()
        if not user_obj:
            # 用户名和密码校验失败  跳转到登陆页面
            return render(request, 'login.html', {'error': '用户名或密码错误'})
        # 登陆成功  初始化权限信息
        init_permission(user_obj, request)
        # 重定向去首页
        return redirect('index')

    return render(request, 'login.html')


def index(request):
    return render(request, 'index.html')
